//
//  MultipleBarChartViewController.swift
//  ChartsDemo-iOS
//
//  Created by Jacob Christie on 2017-07-09.
//  Copyright © 2017 jc. All rights reserved.
//

import UIKit
import Charts

class MultipleBarChartViewController: DemoBaseViewController {
    
    @IBOutlet var chartView: BarChartView!
    
    override var names: Array<String>{
        get{
            return ["datas"]
        }
    }
    
    override func path(for name: String) -> String {
        return BusinessIncomeDegree
    }
    
    override func param(for name: String) -> Dictionary<String,Any> {
        return ["":""]
    }
    
    override func success(for name: String) -> NetSuccess {
        func success(json: JSON)->Void{
            guard let data = json.contents?["data"]?.contents else {
                self.alert("空数据")
                return
                
            }
            
            print(data)
            
            guard let businessCostData = data["businessCostData"]?.dictionary else { return  }
            
            guard let objectCostData = data["objectCostData"]?.dictionary else { return  }
            
            var plain:Array<Double> = []
            
            var predicate: Array<Double> = []
            
            plain = businessCostData.map({ (key,value) -> Double in
                return value.double!
            })
            
            predicate = objectCostData.map({ (key,value) -> Double in
                return value.double!
            })
            
            guard let executeData = data["executeData"]?.dictionary else { return  }
            
            let dataset = executeData.map({ (key,value) -> Double in
                return value.double!
            })
            
            setDataCount(with: plain, predicate: predicate, execute: dataset)
        }
        return success;
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view
        self.options = [.toggleValues,
                        .toggleHighlight,
                        .animateX,
                        .animateY,
                        .animateXY,
                        .saveToGallery,
                        .togglePinchZoom,
                        .toggleAutoScaleMinMax,
                        .toggleData,
                        .toggleBarBorders]
        
        chartView.delegate = self
        
        chartView.chartDescription?.enabled =  false
        
        chartView.doubleTapToZoomEnabled = false
        
        chartView.pinchZoomEnabled = false
        
        chartView.drawBarShadowEnabled = false
        
        let marker = BalloonMarker(color: UIColor(white: 180/255, alpha: 1), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8))
        marker.chartView = chartView
        marker.minimumSize = CGSize(width: 80, height: 40)
        chartView.marker = marker
        
        let l = chartView.legend
        l.horizontalAlignment = .center
        l.verticalAlignment = .top
        l.orientation = .horizontal
        l.drawInside = false
        
        
        l.font = .systemFont(ofSize: 14, weight: .light)
        l.yOffset = 0
        l.xOffset = 10
        l.yEntrySpace = 0
        //        chartView.legend = l
        
        let xAxis = chartView.xAxis
        xAxis.labelFont = .systemFont(ofSize: 10, weight: .light)
        xAxis.granularity = 1
        xAxis.centerAxisLabelsEnabled = true
        xAxis.valueFormatter = IntAxisValueFormatter()
        xAxis.labelPosition = .bottom
        xAxis.drawGridLinesEnabled = false
        
        
        let title = UILabel()
        
        title.text = "单位:万元"
        
        title.left = 10
        
        title.top = 10
        
        title.width = 100
        
        title.height = 20
        
        title.font = UIFont.systemFont(ofSize: 12)
        
        chartView.addSubview(title)
        
        let leftAxisFormatter = NumberFormatter()
        
        leftAxisFormatter.maximumFractionDigits = 1
        
        let leftAxis = chartView.leftAxis
        
        leftAxis.labelFont = .systemFont(ofSize: 10, weight: .light)
        
        leftAxis.valueFormatter = LargeValueFormatter()
        
        leftAxis.spaceTop = 0.35
        
        leftAxis.axisMinimum = 0
        
        chartView.rightAxis.enabled = false
        
        self.load(with: "datas")
    }
    
    override func updateChartData() {
        if self.shouldHideData {
            chartView.data = nil
            return
        }
        
//        self.setDataCount()
    }
    
    func setDataCount(with plain:[Double],predicate:[Double],execute:[Double]) {
        
        let groupSpace = 0.1
        
        let barSpace = 0.05
        
        let barWidth = 0.25
        
        var max = 0.0
        
        for value in plain {
            max = value > max ? value : max
        }
        
        for value in predicate {
            max = value > max ? value : max
        }
        
        for value in execute {
            max = value > max ? value : max
        }
        
        let leftAxis = chartView.leftAxis
        
        if max == 0.0 {
            leftAxis.axisMinimum = 0.0
            
            leftAxis.axisMaximum = 10
        }
        
        var yVals1: Array<BarChartDataEntry> = []
        
        for (index,value) in plain.enumerated() {
            yVals1.append(BarChartDataEntry(x: Double(index), y: value))
        }
        
        var yVals2: Array<BarChartDataEntry> = []
        
        for (index,value) in predicate.enumerated() {
            yVals2.append(BarChartDataEntry(x: Double(index), y: value))
        }
        
        
        var yVals3: Array<BarChartDataEntry> = []
        
        for (index,value) in execute.enumerated() {
            yVals3.append(BarChartDataEntry(x: Double(index), y: value))
        }
        
        let set1 = BarChartDataSet(values: yVals1, label: "计划数据")
        
        set1.setColor(UIColor(red: 49/255, green: 201/255, blue: 102/255, alpha: 1))
        
        set1.drawValuesEnabled = false
        
        let set2 = BarChartDataSet(values: yVals2, label: "预算数据")
        set2.setColor(UIColor(red: 236/255, green: 139/255, blue: 36/255, alpha: 1))
        set2.drawValuesEnabled = false
        
        let set3 = BarChartDataSet(values: yVals3, label: "执行数据")
        set3.setColor(UIColor(red: 47/255, green: 130/255, blue: 228/255, alpha: 1))
        set3.drawValuesEnabled = false
        
        
        let data = BarChartData(dataSets: [set1, set2, set3])
        
        data.setValueFont(.systemFont(ofSize: 10, weight: .light))
        
        data.setValueFormatter(LargeValueFormatter())
        
        // specify the width each bar should have
        data.barWidth = barWidth
        
        // restrict the x-axis range
        chartView.xAxis.axisMinimum = Double(0)
        
        // groupWidthWithGroupSpace(...) is a helper that calculates the width each group needs based on the provided parameters
//        chartView.xAxis.axisMaximum = Double(0) + data.groupWidth(groupSpace: groupSpace, barSpace: barSpace) * Double(5)
        chartView.xAxis.axisMaximum = Double(5)
        
        data.groupBars(fromX: Double(0), groupSpace: groupSpace, barSpace: barSpace)
        
        chartView.data = data
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    override func optionTapped(_ option: Option) {
        super.handleOption(option, forChartView: chartView)
    }
    
    // MARK: - Actions
    @IBAction func slidersValueChanged(_ sender: Any?) {
//        let startYear = 1980
//        let endYear = startYear + Int(sliderX.value)
//
//        sliderTextX.text = "\(startYear)-\(endYear)"
//        sliderTextY.text = "\(Int(sliderY.value))"
        
        self.updateChartData()
    }
}

